<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<select name="sheng">
			<!-- <option value="1">广东省</option>
			<option value="2">湖南省</option> -->
		</select>
		<select name="shi" hidden="">
			<!-- <option value="1">广州市</option>
			<option value="2">中山市</option>
			<option value="3">长沙市</option>
			<option value="4">衡阳市</option> -->
		</select>
		<select name="qu" hidden="">
			<!-- <option value="1">白云区</option>
			<option value="2">黄埔区</option>
			<option value="3">岳麓区</option> -->
		</select>
		
		<script src="../js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			//省市关联
			//1.获取select，然后指定change事件
			$("select[name='sheng']").change(function(){
				//获取被选择的option的value和内容
				let option = $(this).find("option:selected");
				//获取内容和值
				let val = option .val();//值
				let text = option.text(); //内容

				initSelect("select[name='shi']",shiArr,val);
			});
			//市区关联
			$("select[name='shi']").change(function(){
				//获取被选择的option的value和内容
				let option = $(this).find("option:selected");
				//获取内容和值
				let val = option .val();//值
				let text = option.text(); //内容
				
				initSelect("select[name='qu']",quArr,val);
			});
			/** 
			 * 	做三级联动，一定要弄清楚的几点
			 *	1、select标签
			 *	2、jq获取选中的option的val和text
			 *	3、三个select之间的数据必须有关联
			 * */
			 
			let shengArr = [
				{id:1,name:"广东省"},
				{id:2,name:"广西壮族自治区"}
			]
			let shiArr = [
				{id:1,name:"广州市",parentId:1},
				{id:2,name:"中山市",parentId:1},
				{id:3,name:"南宁市",parentId:2},
				{id:4,name:"柳州市",parentId:2}
			]
			let quArr = [
				{id:1,name:"白云区",parentId:1},
				{id:2,name:"黄埔区",parentId:1},
				{id:3,name:"城中区",parentId:4},
				{id:4,name:"鱼峰区",parentId:4},
				{id:5,name:"东区街道",parentId:2},
				{id:6,name:"石岐街道",parentId:2},
				{id:7,name:"江南区",parentId:3},
				{id:8,name:"西乡塘区",parentId:3}
			]
			
			/**
			 * 初始化Select标签内容
			 * @param {Object} selector 选择器  
			 * @param {Object} arr 数组
			 * @param {Object} parentId 父id
			 * */
			
			function initSelect(selector, arr,parentId){
				$(selector).empty();
				$(selector).show();
				if(parentId && typeof (parentId) === "string"){
					parentId = parseInt(parentId);
				}
				for(let item of arr){
					if(parentId && item.parentId !== parentId){
						continue;
					}
					$(selector).append(`<option value="${item.id}">${item.name}</option>`);
				}
			}
			initSelect("select[name='sheng']",shengArr);
		</script>
		
	</body>
</html>
